package edu.nf.meituan.service.user.impl;

import edu.nf.meituan.dao.user.impl.UserDaoImpl;
import edu.nf.meituan.model.user.User;
import edu.nf.meituan.service.exception.CodeException;
import edu.nf.meituan.service.exception.LoginException;
import edu.nf.meituan.service.user.UserService;
import edu.nf.util.MD5Util;
import edu.nf.util.sms.SMSUtil;

/**
 * @Date 2023-06-19
 * @Author qiu
 * 用户业务实现
 */
public class UserServiceImpl implements UserService {

    /**
     * 用户登录
     * @param username 账号
     * @param password 密码
     * @return
     */
    @Override
    public User login(String username, String password) {

        User user = new UserDaoImpl().loginUser(username);
        MD5Util md5Util = new MD5Util();
        if (user.getUserName().equals(username) && md5Util.equals(password,user.getPassword())) {
            return user;
        }
        throw new LoginException(500, "账号或密码错误");

    }

    /**
     * 用户注册
     * @param uName 账号
     * @param pwd 密码
     * @param nickName 匿名
     * @param uPhone 电话
     * @param key  验证码
     * @return
     */
    @Override
    public int registerUser(String uName, String pwd, String nickName, String uPhone, String key) {
        int row = 0;

        // 判断手机号是否注册过
        User user = new UserDaoImpl().equeryUserPhone(uPhone);
        if (user != null) {
            throw new RuntimeException("该手机已注册！");
        }

        // 判断输入的验证码和生成的验证码是否一致
        String send = new SMSUtil().send(uPhone);
        if (key.trim().equals(send)) {
            // 使用 MD5 加密密码
            MD5Util md5Util = new MD5Util();
            row = new UserDaoImpl().registerUser(uName, md5Util.encode(pwd), nickName, uPhone);
            return row;
        }
        try {
            throw new CodeException("验证码错误");
        } catch (CodeException e) {
            throw new RuntimeException(e);
        }

    }

}
